<template>
  <div class="fileUpload-container" v-if="show">
    <input
      v-if="count == 1"
      ref="file"
      class="fileUpload-input"
      type="file"
      @change="bindFilesChange($event)"
    />
    <input
      v-else
      ref="file"
      class="fileUpload-input"
      type="file"
      @change="bindFilesChange($event)"
      multiple
    />
  </div>
</template>
<script>
export default {
  data() {
    return {
      clicked: false,
      show: true,
      type: "image", // 类型 image、audio、video、file
      count: 0, //数量默认为0就是需要外部传入大于0的数值来触发updated方法来唤起选择文件
      callback: function() {}
    };
  },
  methods: {
    bindFilesChange(event) {
      var types = [];
      if (this.type == "image") {
        types = ["image/jpeg", "image/png", "image/gif"];
      } else if (this.type == "audio") {
        types = ["audio/mpeg", "audio/ogg", "audio/x-m4a"];
      } else if (this.type == "video") {
        types = [
          "video/3gpp",
          "video/mp4",
          "video/mpeg",
          "video/quicktime",
          "video/webm",
          "video/x-flv",
          "video/x-m4v",
          "video/x-ms-wmv",
          "video/x-msvideo"
        ];
      } else if (this.type == "file") {
        types = [
          "application/msword",
          "application/pdf",
          "application/rtf",
          "application/vnd.ms-excel",
          "application/vnd.ms-powerpoint",
          "application/x-rar-compressed",
          "application/x-shockwave-flash s",
          "application/zip"
        ];
      }
      var newFiles = [];
      const files = event.target.files;
      for (var i = 0; i < files.length; i++) {
        const file = files[i];
        if (types.indexOf(file.type) == -1 && this.callback) {
          this.callback("不支持此文件：" + file.type);
          return;
        }
        if (i < this.count) {
          newFiles.push(file);
        }
      }
      if (this.callback) this.callback(newFiles.length == 1 ? newFiles[0] : newFiles);
    }
  },
  updated() {
    if (this.clicked) return;
    // 点击
    this.$refs.file.click();
    this.clicked = true;
    this.show = false;
  }
};
</script>
<style scoped>
.fileUpload-container {
  display: none;
}
.fileUpload-input {
  display: none;
}
</style>